package com.cheng.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cheng.domain.system.Permission;
import com.cheng.domain.system.Role;
import com.cheng.domain.system.User;
import com.cheng.service.system.PermissionService;
import com.cheng.service.system.RoleService;
import com.cheng.service.system.UserService;

//@Service("bosRealm")
public class BosRealm extends AuthorizingRealm {

	@Autowired
	private UserService userservice;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	
	//授权管理
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection token) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		System.out.println("授权管理");
		// 根据当前登录用户 查询对应角色和权限
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		// 调用业务层，查询角色
		List<Role> roles = roleService.findByUser(user);
		for (Role role : roles) {
			authorizationInfo.addRole(role.getKeyword());
		}
		// 调用业务层，查询权限
		List<Permission> permissions = permissionService.findByUser(user);
		for (Permission permission : permissions) {
			authorizationInfo.addStringPermission(permission.getKeyword());
		}

		return authorizationInfo;
	}

	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//将参数对象token转化
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		User user = userservice.findByUserName(usernamePasswordToken.getUsername());
		System.out.println(user);
		if (user == null) {
			//用户不存在，返回null
			return null;
		}else{
			// 用户名存在
			// 参数一： 期望登录后，保存在Subject中信息
			// 参数二： 如果返回为null 说明用户不存在，报用户名
			// 参数三 ：realm名称
			return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		}
	}

}
